#!/bin/bash
# DVC Metadata Upload Hook (post-commit version)
# Uploads .dvc files after committing to git

set -e

# Check if dvc is installed
if ! command -v dvc &> /dev/null; then
    exit 0
fi

# Function to print timestamped messages
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

# DVC_SERVER_IP and DVC_SERVER_PORT come from /etc/environment
DVC_SERVER_URL="http://${DVC_SERVER_IP:-dummyIP}:${DVC_SERVER_PORT:-dummyPort}/api/data/upload-metadata"
log "DVC metadata server URL: $DVC_SERVER_URL"

# Get DVC user if available, fallback to system user
DVC_USER=$(whoami)@hillstonenet.com

REPO_ROOT=$(git rev-parse --show-toplevel)
cd "$REPO_ROOT"

# Get project name from remote URL or fallback to directory name
get_project_name() {
    local project_name=$(git remote get-url origin 2>/dev/null | sed -e 's/.*\///' -e 's/\.git$//')
    if [[ -z "$project_name" ]]; then
        project_name=$(basename "$REPO_ROOT")
    fi
    echo "$project_name"
}

PROJECT_NAME=$(get_project_name)
log "Starting DVC metadata upload for user: $DVC_USER"
log "Project: $PROJECT_NAME"

git diff-tree --no-commit-id --name-only -r HEAD | grep '\.dvc$' | while read -r dvc_file; do
    if [[ "$dvc_file" == *".git"* ]]; then
        continue
    fi
    
    log "Uploading metadata for: $dvc_file"
    
    curl -X POST "$DVC_SERVER_URL" \
         -F "dvc_file=@$dvc_file" \
         -F "username=$DVC_USER" \
         -F "project_name=$PROJECT_NAME" \
         --silent --show-error --fail
    
    if [ $? -eq 0 ]; then
        log "✓ Successfully uploaded: $dvc_file"
    else
        log "✗ Failed to upload: $dvc_file" >&2
    fi
done

log "DVC metadata upload completed."
